package commands

import (
	"strings"
	"trpg-message/entity"
)

type Command interface {
	Handle(message entity.Message, arg string) string
}

func Dispatch(messageEntity entity.Message) (bool, string) {
	message := messageEntity.Content
	for k, v := range Commands {
		if message == "" {
			return false, ""
		}
		if f, arg := isCommand(message, k, rune(message[0])); f {
			return true, v.Handle(messageEntity, arg)
		}
	}
	return false, ""
}

func isCommand(message string, command string, startWith rune) (bool, string) {
	f := strings.HasPrefix(message, string(startWith)+command+" ") || (strings.LastIndex(message, string(startWith)+command) != -1 && strings.LastIndex(message, string(startWith)+command) == len(message)-len(string(startWith)+command))
	if f {
		arr := strings.SplitN(message, " ", 2)
		if len(arr) < 2 {
			return true, ""
		} else {
			return true, arr[1]
		}
	} else {
		return false, ""
	}
}

type CommonCommand struct {
}

func (command CommonCommand) Handle(message entity.Message, arg string) string {
	return "不存在的指令，请重新输入捏~"
}
